//
//  Team9DesignerVc.m
//  Team9Project
//
//  Created by 朱嘉祺 on 15/10/15.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "Team9DesignerVc.h"
#import "Team9ExpertHeaderView.h"
#import "JQAFNetworkTool.h"
#import "Team9ExpertUser_home_infoModel.h"
#import "Team9ExpertPro_serviceModel.h"
#import "Team9ExpertCell.h"
#import <Masonry.h>
#import "Team9DesignModel.h"
#import "Team9ExpertDetailView.h"
#import "Team9ExpertDiscussTableViewCell.h"
#import "Team9ExpertDiscussModel.h"
#import "Team9ExpertIdeabookColletionCell.h"
#import "Team9ExpertIdeabookModel.h"
#import "Team9ExpertFootView.h"
#import "Team9ExpertSectionHeaderView.h"
#import "Team9s_discussViewController.h"
#import "Team9DesignVC.h"
#import <GPUImage.h>

@interface Team9DesignerVc ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) Team9ExpertHeaderView *headView;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSArray *array;

@property(nonatomic, strong) UIScrollView *darkView;
@property(nonatomic, strong) Team9ExpertDetailView *detailView;
@property(nonatomic, strong) NSArray *topicArray;
@property(nonatomic, strong) NSArray *ideabookArray;

@property(nonatomic, copy) NSString *workTotal;
@property(nonatomic, copy) NSString *topicTotal;
@property(nonatomic, copy) NSString *ideabookToal;

@property(nonatomic, strong) Team9ExpertFootView *footView;
@property(nonatomic, strong) UIImageView *startImage;
@property(nonatomic, retain) GPUImageGaussianBlurFilter *blurFilter;

@end
@implementation Team9DesignerVc

// 用一个高斯模糊图层覆盖view 产生模糊效果在移除

// 开始动画
- (void)startAnimation {
    
    self.startImage = [[UIImageView alloc] initWithFrame:self.view.bounds];

    self.startImage.image = [self convertViewToImage];
    
    self.blurFilter = [[GPUImageGaussianBlurFilter alloc] init];
    self.blurFilter.blurRadiusInPixels = 0;
    self.startImage.image =
    [self.blurFilter imageByFilteringImage:self.startImage.image];
    
    // 讲设置好的UIVisualEffectView添加到要模糊的视图层上
    
    [self.view addSubview:self.startImage];
    [self shopAnimation];
}
// 停止动画
- (void)shopAnimation {
    
    [UIView animateWithDuration:0.6
                     animations:^{
            self.startImage.alpha = 0;
                         
                     }completion:^(BOOL finished) {
            [self.startImage removeFromSuperview];
                     }] ;
    [UIView animateWithDuration:0.0001
                     animations:^{
                         [UIView setAnimationDelay:0.2];
            self.blurFilter.blurRadiusInPixels = 5;
            self.startImage.image = [self.blurFilter imageByFilteringImage:self.startImage.image];
                     }];
}
// 刷新 image
-(void)updateBlur
{
    self.startImage.image = [self convertViewToImage];
}
// 截屏 image
-(UIImage *)convertViewToImage
{
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
} 

- (void)dealloc{
    _headView = nil;
}
- (void)viewDidLoad {
  [super viewDidLoad];

    self.headView = [[Team9ExpertHeaderView alloc]
        initWithFrame:CGRectMake(0, 0, WIDTH, 120 + 260 * WIDTH / 375)];
    self.headView.userId = self.Id;
    // 点击头视图button 进入详细界面
    __weak __typeof(self)weakSelf = self;
    self.headView.block = ^{
        [weakSelf startAnimation];
        [weakSelf.darkView setHidden:NO];
    };
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    
    // 自己做了一个放回按钮
    Team9BaseView *backView = [[Team9BaseView alloc] initWithType:ViewTYpeLight];
    backView.frame = CGRectMake(0, 0, WIDTH, 64);
    [self.view addSubview:backView];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame = CGRectMake(0, 20, 60, 44);
    [backView addSubview:backButton];
    
    if ([Team9EveningType shareEvening].eveningFailling) {
        [backButton setImage:[UIImage imageNamed:@"back2"] forState:UIControlStateNormal];
    } else [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.footView = [[Team9ExpertFootView alloc] init];
    self.footView.frame = CGRectMake(0, 0, WIDTH, 40 * 3 * WIDTH / 375);
    
    self.footView.Id =  self.Id;
    self.footView.vc = self;
    
    self.tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0);
    
    self.empty = [Team9EmptyTool toolWithScrollView:self.tableView];
    [self createDarkView];
    [self createData];
    
}



#pragma mark 初始化相信内容的view

- (void)createDarkView{

    self.darkView = [UIScrollView new];
    self.darkView.bounces = NO;
    [self.view addSubview:_darkView];
    [_darkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(20, 0, 0, 0));
    }];
    UIView *view = [UIView new];
    [self.darkView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
         make.edges.equalTo(self.view);
    }];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.8f;
    
    self.detailView = [[Team9ExpertDetailView alloc] init];
    [self.darkView addSubview:_detailView];
    
    [_detailView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.darkView).priorityLow();
        make.width.equalTo(@(WIDTH));
        make.top.mas_greaterThanOrEqualTo(self.darkView);
        make.bottom.mas_lessThanOrEqualTo(self.darkView);
    }];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"X" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.darkView addSubview:button];
    [button addTarget:self action:@selector(hideDark) forControlEvents:UIControlEventTouchUpInside];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-49 / 2);
        make.width.height.equalTo(@49);
        make.centerX.equalTo(self.view);
    }];

    [self.darkView setHidden:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)hideDark{
    [self startAnimation];
    [self.darkView setHidden:YES];
}

- (void)setArray:(NSArray *)array
{
    if (_array != array) {
        _array = array;
        [self.tableView reloadData];
    }
}



#pragma mark methods for tableView potrol

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        Team9DesignModel *model = self.array[indexPath.row];
        Team9DesignVC *vc = [Team9DesignVC new];
        vc.url = [NSString stringWithFormat:@"http://api.meilijia.com/app/collection_page2?col_id=%@&tab=photo", model.modelId];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.array.count;
    }
    if (section == 1 && _topicArray.count) {
        return 1;
    }
    if (section == 2 && _ideabookArray.count) {
        return 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 && _array.count) {
        return 44.0f;
    }
    if (section == 1 && _topicArray.count) {
        return 44.0f;
    }
    if (section == 2 && _ideabookArray.count) {
        return 44.0f;
    }
    return 0.0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 40 + 250 * WIDTH / 375;
    }
    if (indexPath.section == 1) {
        return (150 * self.topicArray.count + 30)* WIDTH/ 375 + 20;
    }
    if (indexPath.section == 2) {
        CGFloat n = (self.ideabookArray.count + 1) / 2;
        return WIDTH / 2 * (int)n + 30 * WIDTH / 375 + 10;
    }
    return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    Team9ExpertSectionHeaderView *view =[[Team9ExpertSectionHeaderView alloc] init];
    if (section == 0 && _array.count) {
      view.titleLabel.text = [NSString stringWithFormat:@"已验证作品 %@", self.workTotal];
    } else if (section == 1 && _topicArray.count) {
      view.titleLabel.text =  [NSString stringWithFormat:@"讨论 %@", self.topicTotal];
    } else if (section == 2 && _ideabookArray.count) {
      view.titleLabel.text =  [NSString stringWithFormat:@"灵感画册 %@", self.ideabookToal];
    }
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        static NSString *reuse = @"expertCellReuse";
        Team9ExpertCell *cell =[tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[Team9ExpertCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        Team9DesignModel *model = self.array[indexPath.row];
        cell.model = model;
        return cell;
    }
    if (indexPath.section == 1) {
        static NSString *reuse = @"DiscussTableViewCellReuse";
        Team9ExpertDiscussTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[Team9ExpertDiscussTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        cell.Id = _Id;
        cell.vc = self;
        __weak __typeof(self)weakSelf = self;
        [cell setBlock:^(NSInteger index) {
            Team9ExpertDiscussModel *model = weakSelf.topicArray[index];
            Team9s_discussViewController *vc = [Team9s_discussViewController new];
            vc.topicID = model.modelId;
            weakSelf.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        cell.array = self.topicArray;
        return cell;
    }
    if (indexPath.section == 2) {
        static NSString *reuse = @"IdeabookColletionCellReuse";
        Team9ExpertIdeabookColletionCell *cell =[tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[Team9ExpertIdeabookColletionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        __weak __typeof(self)weakSelf = self;
        cell.Id = _Id;
        cell.vc = self;
        [cell setBlock:^(NSInteger index) {
            weakSelf.navigationController.navigationBar.hidden = NO;
            Team9ExpertIdeabookModel *model = weakSelf.ideabookArray[index];
            Team9DesignVC *vc = [Team9DesignVC new];
            vc.url = [NSString stringWithFormat:@"http://api.meilijia.com/app/collection_page2?col_id=%@&tab=photo", model.col_id];
            //            NSLog(@"%@", model.modelId);
            weakSelf.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            //            weakSelf.hidesBottomBarWhenPushed = NO;
        }];
        cell.array = self.ideabookArray;
        return cell;
    }
    return nil;

}
#pragma mark 网络请求
- (void)createData{
//    NSLog(@"%@", _url);
    
    [Team9RefreshTool getUrl:_url success:^(id result) {
        self.tableView.tableHeaderView = self.headView;
        self.tableView.tableFooterView = _footView;
        self.workTotal = result[@"data"][@"user_home_work_list"][@"total"];
        self.topicTotal = result[@"data"][@"user_home_topic_list"][@"topic_total"];
        self.ideabookToal = result[@"data"][@"user_home_ideabook_list"][@"total"];
        
        self.ideabookArray = [Team9ExpertIdeabookModel baseModelByArr:result[@"data"][@"user_home_ideabook_list"][@"collections"]];
        self.topicArray = [Team9ExpertDiscussModel baseModelByArr:result[@"data"][@"user_home_topic_list"][@"topic_list"]];
        
        [self.headView.serviceModel setValuesForKeysWithDictionary: result[@"data"][@"user_home_info"][@"pro_service"]];
        [self.headView.userModel setValuesForKeysWithDictionary: result[@"data"][@"user_home_info"][@"user_info"]];
        [self.headView reload];
        self.detailView.string = self.headView.userModel.nick;
        self.detailView.model = self.headView.serviceModel;
        self.footView.model = self.headView.userModel;
        self.array = [Team9DesignModel baseModelByArr:result[@"data"][@"user_home_work_list"][@"collections"]];
        [self.darkView setContentOffset:CGPointZero];
    } scrollView:self.tableView empty:self.empty];
}
- (void)pop{
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController.navigationBar setHidden:NO];
}
@end
